﻿namespace RainbowNavBar.Function
{
    public class GlobalFunction
    {
        /// <summary>
        /// 封装：显示子窗口并添加遮罩层
        /// </summary>
        /// <param name="parent">窗体</param>
        /// <param name="child">子窗体</param>
        /// <param name="maskLayer">遮罩层</param>
        public static void ShowChildWindowWithMask(Window parent, Window child, UIElement maskLayer)
        {
            if (maskLayer != null)
            {
                maskLayer.Visibility = Visibility.Visible; // 显示遮罩层
            }

            child.Owner = parent; // 设置父窗口
            child.WindowStartupLocation = WindowStartupLocation.CenterOwner;

            // 子窗口关闭时隐藏遮罩层
            child.Closed += (s, e) =>
            {
                if (maskLayer != null)
                {
                    maskLayer.Visibility = Visibility.Collapsed;
                }
            };

            child.Show();
        }

        /// <summary>
        /// 将 Color 转换为十六进制颜色值字符串
        /// </summary>
        /// <param name="color">要转换的 Color 对象</param>
        /// <param name="includeAlpha">是否包含 Alpha 通道值</param>
        /// <param name="sign">是否包含#</param>
        /// <param name="signChar">字符(默认：#)</param>
        /// <returns>十六进制颜色值字符串</returns>
        public static string ToHexString(Color color, bool includeAlpha = false, bool sign = false, string signChar = "#")
        {
            string _color = includeAlpha ? $"{color.A:X2}{color.R:X2}{color.G:X2}{color.B:X2}" : $"{color.R:X2}{color.G:X2}{color.B:X2}";
            return sign ? signChar + _color : _color;
        }

        /// <summary>
        /// 比较两种Brush类型是否相同
        /// </summary>
        /// <param name="brush1"></param>
        /// <param name="brush2"></param>
        /// <returns></returns>
        public static bool BrushesAreEqual(Brush brush1, Brush brush2)
        {
            // 如果两个都是 null，认为相等
            if (brush1 == null && brush2 == null)
            {
                return true;
            }

            // 如果其中一个是 null，另一个不是，认为不相等
            if (brush1 == null || brush2 == null)
            {
                return false;
            }

            // 如果都是 SolidColorBrush，比较颜色
            if (brush1 is SolidColorBrush solidBrush1 && brush2 is SolidColorBrush solidBrush2)
            {
                return solidBrush1.Color == solidBrush2.Color;
            }

            // 如果是其他类型的 Brush，这里可以继续添加更多比较逻辑
            // 例如对于 LinearGradientBrush、ImageBrush 等类型，比较它们的属性

            // 如果是不同类型的 Brush，认为它们不相等
            return false;
        }

        #region 获取网站图标

        /// <summary>
        /// 创建网络请求对象
        /// </summary>
        private static readonly System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();

        /// <summary>
        /// 根据给定的网址获取网站的favicon图标URL
        /// </summary>
        /// <param name="url">网站地址</param>
        /// <returns>返回图标URL</returns>
        public static async Task<string> GetFaviconAsync(bool b, string url)
        {
            try
            {
                // 如果URL没有以"HTTP"或"HTTPS"开头，默认添加http://
                if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
                {
                    url = "http://" + url;
                }

                // 获取网页内容
                System.Net.Http.HttpResponseMessage response = await httpClient.GetAsync(url);
                string html = await response.Content.ReadAsStringAsync();

                // 正则表达式，查找favicon的URL
                var regex = new Regex(@"<link[^>]*rel=""(?:icon|shortcut icon)""[^>]*href=""([^""]+)""", RegexOptions.IgnoreCase);
                var match = regex.Match(html);

                if (match.Success)
                {
                    string faviconUrl = match.Groups[1].Value;

                    // 如果faviconUrl是相对路径，则转换为绝对路径
                    if (!faviconUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    {
                        Uri baseUri = new Uri(url);
                        Uri absoluteUri = new Uri(baseUri, faviconUrl);
                        return absoluteUri.ToString();
                    }

                    return faviconUrl;
                }
                else
                {
                    return null; // 没有找到favicon图标
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error fetching favicon: " + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 根据给定的网址获取网站的favicon图标并返回BitmapImage
        /// </summary>
        /// <param name="url">网站地址</param>
        /// <returns>返回网站favicon的BitmapImage</returns>
        public static async Task<BitmapImage> GetFaviconAsync(string url)
        {
            try
            {
                // 如果URL没有以"HTTP"或"HTTPS"开头，默认添加http://
                if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
                {
                    url = "http://" + url;
                }

                // 获取网页内容
                System.Net.Http.HttpResponseMessage response = await httpClient.GetAsync(url);
                string html = await response.Content.ReadAsStringAsync();

                // 正则表达式，查找favicon的URL
                var regex = new Regex(@"<link[^>]*rel=""(?:icon|shortcut icon)""[^>]*href=""([^""]+)""", RegexOptions.IgnoreCase);
                var match = regex.Match(html);

                if (match.Success)
                {
                    string faviconUrl = match.Groups[1].Value;

                    // 如果faviconUrl是相对路径，则转换为绝对路径
                    if (!faviconUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    {
                        Uri baseUri = new(url);
                        Uri absoluteUri = new(baseUri, faviconUrl);
                        faviconUrl = absoluteUri.ToString();
                    }

                    // 下载 favicon 图标并转换为 BitmapImage
                    var imageBytes = await DownloadImageAsync(faviconUrl);
                    return ConvertToBitmapImage(imageBytes);
                }
                else
                {
                    return null; // 没有找到favicon图标
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error fetching favicon: " + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 下载图标
        /// </summary>
        /// <param name="url">图标URL</param>
        /// <returns>返回图标的字节数组</returns>
        private static async Task<byte[]> DownloadImageAsync(string url)
        {
            try
            {
                System.Net.Http.HttpResponseMessage response = await httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsByteArrayAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error downloading image: " + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 将字节数组转换为BitmapImage
        /// </summary>
        /// <param name="imageBytes">图像字节数组</param>
        /// <returns>返回BitmapImage</returns>
        private static BitmapImage ConvertToBitmapImage(byte[] imageBytes)
        {
            if (imageBytes == null || imageBytes.Length == 0)
                return null;

            using (var stream = new System.IO.MemoryStream(imageBytes))
            {
                var bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = stream;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                return bitmapImage;
            }
        }

        #endregion

    }
}
